﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OASys.Biz.BizAccess;
using OASys.Entity;
using OASys.Web.Base;

namespace OASys.Web.Areas.ModuleWF.Models
{
	public class ModelWorkFlowStepIndex : BaseModel
	{
		private BizWFFlowSteps bizWFFlowSteps;
		public Guid? FlowID
		{
			get;
			set;
		}

		public IList<WFFlowSteps> Steps
		{
			get;
			set;
		}

		public void RetriveData()
		{
			Steps = bizWFFlowSteps.ListBy(x => x.FlowID == FlowID);
		}

	}

	public class ModelWorkFlowStepCreate : BaseModel
	{
		private BizWFFlowSteps bizWFFlowSteps;

		public Guid? FlowID
		{
			get;
			set;
		}

		public Guid? CurrentStepId
		{
			get;
			set;
		}

		public WFFlowSteps WFFlowSteps
		{
			get;
			set;
		}


		/// <summary>
		/// 新增或者修改
		/// </summary>
		/// <param name="sampleCreateModel"></param>
		public void Save()
		{
			WFFlowSteps currentStep = null;
			WFFlowSteps nextStep = null;
			if (CurrentStepId != null)
			{
				currentStep = bizWFFlowSteps.GetByID(CurrentStepId);
				nextStep = bizWFFlowSteps.GetByID(currentStep.NextStepID);
			}
			else
			{
				var steps = bizWFFlowSteps.ListBy(x => x.FlowID == FlowID);
				var step = steps.FirstOrDefault(x => x.NextStepID == null);
				while (step != null)
				{
					var temp = steps.FirstOrDefault(x => x.NextStepID == step.ID);
					if (temp == null)
						break;
					step = temp;
				}
				if (step != null)
					WFFlowSteps.NextStepID = step.ID;
			}
			if (nextStep != null)
				WFFlowSteps.NextStepID = nextStep.ID;

			WFFlowSteps.FlowID = FlowID;
			bizWFFlowSteps.SaveOrUpdate(WFFlowSteps);
			if (currentStep != null)
			{
				currentStep.NextStepID = WFFlowSteps.ID;
				bizWFFlowSteps.SaveOrUpdate(currentStep);
			}
		}

	}

	public class ModelWorkFlowStepEdit : BaseModel
	{
		private BizWFFlowSteps bizWFFlowSteps;
		public Guid? ID
		{
			get;
			set;
		}

		public WFFlowSteps WFFlowSteps
		{
			get;
			set;
		}

		public void RetriveData()
		{
			WFFlowSteps = bizWFFlowSteps.GetByID(ID);
		}

		public void Save()
		{
			var dbEntity = bizWFFlowSteps.GetByID(WFFlowSteps.ID);
			dbEntity.StepName = WFFlowSteps.StepName;
			bizWFFlowSteps.SaveOrUpdate(dbEntity);
		}

	}

	public class ModelWorkFlowStepDelete : BaseModel
	{
		private BizWFFlowSteps bizWFFlowSteps;
		public Guid? ID
		{
			get;
			set;
		}

		public void Delete()
		{
			var current = bizWFFlowSteps.GetFirst(x => x.ID == ID);
			var pre = bizWFFlowSteps.GetFirst(x => x.NextStepID == current.ID);
			if (pre != null)
			{
				pre.NextStepID = current.NextStepID;
				bizWFFlowSteps.SaveOrUpdate(pre);
			}
			bizWFFlowSteps.Delete(current);

		}

	}
}